<template>
  <view class="my-coupon">
    <view class="line"></view>
    <!-- 顶部tab -->
    <view class="tab-box">
    	<u-tabs-swiper 
        ref="uTabs" 
        :list="list" 
        :current="current" 
        @change="tabsChange" 
        :is-scroll="false"
        active-color="#333"
        inactive-color="#666"
        swiperWidth="750" 
        bar-width="80"
        :bar-style="barActiveStyle"
      ></u-tabs-swiper>
    </view>
    
    <view class="content">
      <page-loading :show="showPage" height="100%">
        <swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
        	<swiper-item class="swiper-item" v-for="(item, index) in result" :key="index">
        		<scroll-view class="scroll-view" scroll-y @scrolltolower="onLoadmore">
        	    <u-empty mode="coupon" v-if="item.data.length <= 0 && item.isEnd"></u-empty>
        	    <view style="overflow: hidden;" v-else>
        	      <view v-for="(i, k) in item.data" :key="k">
                  <card-item @click="jumpPage" :item="i" v-if="i.card_Type" :type='type' :id='id'/>
        	        <coupon-item @click="jumpPage" :item="i" :type="result[index].couponClass" v-else-if="!i.is_Package" />
        	        <set-meal-item @click="jumpPage" :item="i" v-else />
        	      </view>
        	      
        	      <view class="loading-status"><u-loadmore :status="item.status" /></view>
        	    </view>
        		</scroll-view>
        	</swiper-item>
        </swiper>
      </page-loading>
    </view>
  </view>
</template>

<script>
const dayjs = require('@/utils/dayjs.js')
import couponItem from './components/couponItem.vue' // 优惠券列表组件
import setMealItem from './components/setMealItem.vue' // 套餐列表组件
import cardItem from './components/cardItem.vue' // 洗车会员卡列表组件
export default {
  components: {
    couponItem,
    setMealItem,
    cardItem
  },
  data() {
    return {
      barActiveStyle: {
        'background': 'linear-gradient(0deg, #FBB000, #FFE23E)'
      }, // tab选中是下划线样式
      /* list: [
				{
					name: '全部'
				}, 
				{
					name: '购车券'
				}, 
				{
					name: '养车卡券'
				}, 
				{
					name: '套餐卡'
				}, 
				{
					name: '自助洗车'
				},
				{
					name: '其他'
				}
			], */
			list: [
				/* {
					name: '智动洗车'
				}, */
				{
					name: '养车卡券'
				},
				{
					name: '自助洗车'
				}, 
				
				{
					name: '其他'
				}
			], 
			// tab数据列表
      current: 0, // tabs组件的current值
      swiperCurrent: 0 ,// swiper组件的current值
      /* result: [
        {
          couponClass: 0,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          couponClass: 3,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          couponClass: 2,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          couponClass: 4,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
				{
				  couponClass: 6,
				  PageIndex: 1,
				  PageSize: 20,
				  isEnd: false,
				  loading: false,
				  status: 'loading',
				  data: []
				},
        {
          couponClass: 1,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        }
      ], */
      result: [
        {//智动洗车
          couponClass: 0,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {//自助洗车
          couponClass: 6,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
      	{//养车卡券
      	  couponClass: 2,
      	  PageIndex: 1,
      	  PageSize: 20,
      	  isEnd: false,
      	  loading: false,
      	  status: 'loading',
      	  data: []
      	},
        {
          couponClass: 1,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        }
      ],
			from: '', // 页面来源 用于点击套餐判断，如果没有值就跳转详情页
      mobile: '', // 用户手机号
      showPage: false,
			type:''
    }
  },
  computed: {
    // 订单信息
    orderinfo() {
      return this.$store.state.maintenanceOrder
    }
  },
  onLoad(option) {
    this.current = Number(option.status) || 0
    this.swiperCurrent = Number(option.status) || 0
    this.from = option.from || ''
		this.id = option.id || ''
    this.mobile = option.mobile || ''
		this.type = option.type || ''
    let userinfo = uni.getStorageSync('Ztc_C_USER_INFO')
    if(!this.mobile && userinfo) {
      this.mobile = userinfo.mobile
    }
    this.getList()
  },
  methods: {
    // 点击tan切换
    tabsChange(index) {
      this.swiperCurrent = index;
      this.getList()
    },
    transition(e) {
      let dx = e.detail.dx;
      this.$refs.uTabs.setDx(dx);
    },
    animationfinish(e) {
      let current = e.detail.current;
      this.$refs.uTabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
      this.getList()
    },
    // 禁用swiper滑动
    stopTouchMove() {
      return false
    },
    onLoadmore() {
      this.getList()
    },
    // 跳转页面
    jumpPage(data) {
			console.log(data,'id')
      if(data.card_Type && !this.from) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/autoWashDetails?id=${data.id}&cardId=${data.self_Service_Car_Wash_Card_Id}&purchase=${data.purchase_Channel}`
        })
      } else if(!data.is_Package && !this.from) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/detail?id=${data.id}&type=${data.coupon_Class}`
        })
        this.$store.commit('couponInfo', data)
      } else if(data.is_Package && !this.from) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/setMealDetail?id=${data.id}&name=${encodeURIComponent(data.coupon_package_name)}`
        })
      } else {
        // 检测优惠券
        this.checkCoupon(data)
      }
    },
    // 计算总共有多少页
    pageCount (totalnum,limit){
      return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0
    },
    // 获取列表数据
    async getList(type) {
      let list = this.result[this.swiperCurrent]
      if (type) {
        list.PageIndex = 1
        list.isEnd = false
        list.loading = false
        list.status = 'loading'
      }
      if (list.loading || list.isEnd) {
        return false
      }
      list.loading = true
      this.$set(this.result, this.swiperCurrent, list)
      try{
        let res = null
        if(list.couponClass === 6) {
          res = await this.$api.user.GetMyCardList({
            pageIndex: list.PageIndex,
            pageSize: list.PageSize,
          })
        } else {
          res = await this.$api.user.GetCouponList({
            coupon_class: list.couponClass,
            pageIndex: list.PageIndex,
            pageSize: list.PageSize,
            mobile: this.mobile
          })
        }
        this.showPage = true
        
        let couponlist = res.data.list.map(item => {
          if(list.couponClass === 6) {
            item.deadline = dayjs(item.deadline).format('YYYY-MM-DD HH:mm:ss')
            item.day = dayjs(item.deadline).diff(dayjs(),'day') + 1
          }
          return item
        })
        if (type) {
          list.data = []
        }
        
        if(couponlist.length <= 0 || list.PageIndex >= this.pageCount(res.data.total, list.PageSize)) {
          list.isEnd = true
          list.status = 'nomore'
        }
        
        if (couponlist.length > 0) {
          list.data = list.data.concat(couponlist)
          list.PageIndex = list.PageIndex + 1
        }
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }catch(e){
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }
      
    },
    // 检测优惠券
    checkCoupon(data) {
      if (!this.orderinfo) {
        let orderinfo = sessionStorage.maintenanceOrder ? JSON.parse(sessionStorage.maintenanceOrder) : []
        this.$store.commit('maintenanceOrder', orderinfo)
      }
      let params = {
        goodsList: [],
        serviceFeeList: [],
        discountTotalAmount: 0
      }
      this.orderinfo.goodsList.map(item => {
        item.maintenanceGoodsLists.map(i => {
          i.count = i.amount
          params.goodsList.push(i)
        })
      })
      this.orderinfo.serviceFeeList.map(item => {
        params.serviceFeeList.push(item)
      })
      // if(this.orderinfo.setMealInfo) {
      //   params.selectedCouponId = this.orderinfo.setMealInfo
      // }
      // if(this.orderinfo.couponInfo) {
      //   params.selectedCouponDetailsId = this.orderinfo.couponInfo
      // }
      if(data.is_Package) {
        params.selectedCouponId = data.id
      } else {
        params.selectedCouponDetailsId = data.cid
      }
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      this.$api.maintenanceOrder.CheckCouponsByGoods(params).then(res => {
        uni.hideLoading()
        if(res.code === 200) {
          data.discountTotalAmount = -res.data.discountTotalAmount
          uni.$emit('changeCoupon', {
            data,
            goodsList: res.data.goodsList,
            discountTotalAmount: -res.data.discountTotalAmount
          })
          uni.showToast({
            icon: 'none',
            title: '已到最大优惠金额，暂时无法使用'
          })
          uni.navigateBack({
            delta: 1
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg
          })
        }
      }).then(err => {
        uni.hideLoading()
      })
    }
  }
}
</script>

<style>
page{
  background-color: #f6f6f6;
}
</style>

<style lang="scss">
page{
  height: 100%;
}
.my-coupon{
  height: 100%;
  display: flex;
  flex-direction: column;
  .line{
    background-color: #f6f6f6;
    height: 2rpx;
    width: 100%;
  }
  .content{
    flex: 1;
    overflow: hidden;
  }
  .swiper, .swiper-item, .scroll-view{
    height: 100%;
  }
  .loading-status{
    padding: 40rpx 0;
  }
  .coupon-item:last-child{
    margin-bottom: 0 !important;
  }
}


</style>
